package midware

import (
	"runtime/debug"
	"shop/monitor"
	"shop/utils/result"
	"time"

	"github.com/cihub/seelog"
	"github.com/gin-gonic/gin"
)

// Recover 自定义panic异常处理，并进行api打点记录
func Recover(c *gin.Context) {
	startTime := time.Now().UnixNano()
	// seelog.Debugf("path: %s, headers: %v", c.FullPath(), c.Request.Header)
	defer func() {
		endTime := time.Now().UnixNano()
		// api耗时计算
		monitor.HttpDurations.WithLabelValues(c.Request.Method, c.FullPath()).Observe(float64(endTime-startTime) / 1000000) // 毫秒

		if err := recover(); err != nil {
			seelog.Errorf("panic err:%v", err)
			debug.PrintStack()
			result.RenderResult(c, result.Fail("server inner error(panic recover)"))
			// api调用次数统计
			monitor.ApiCounter.WithLabelValues(c.Request.Method, c.FullPath(), "panic").Inc()
			c.Abort()
		}
	}()
	c.Next()
	// api调用次数统计
	monitor.ApiCounter.WithLabelValues(c.Request.Method, c.FullPath(), "success").Inc()
}
